import java.lang.reflect.Method;
import jdk.vm.ci.code.site.DataPatch;
import jdk.vm.ci.code.site.Mark;
import jdk.vm.ci.code.site.Site;
import jdk.vm.ci.hotspot.HotSpotCompiledCode;
import jdk.vm.ci.hotspot.HotSpotCompiledNmethod;
import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.runtime.JVMCI;
import jdk.vm.ci.runtime.JVMCICompiler;

// javac --add-modules jdk.internal.vm.ci --add-exports jdk.internal.vm.ci/jdk.vm.ci.code=ALL-UNNAMED --add-exports jdk.internal.vm.ci/jdk.vm.ci.code.site=ALL-UNNAMED --add-exports jdk.internal.vm.ci/jdk.vm.ci.hotspot=ALL-UNNAMED --add-exports jdk.internal.vm.ci/jdk.vm.ci.runtime=ALL-UNNAMED --add-exports jdk.internal.vm.ci/jdk.vm.ci.meta=ALL-UNNAMED TestNativeCodeBug.java
// java --add-opens jdk.internal.vm.ci/jdk.vm.ci.code=ALL-UNNAMED --add-opens jdk.internal.vm.ci/jdk.vm.ci.code.site=ALL-UNNAMED --add-opens jdk.internal.vm.ci/jdk.vm.ci.hotspot=ALL-UNNAMED --add-opens jdk.internal.vm.ci/jdk.vm.ci.runtime=ALL-UNNAMED --add-opens jdk.internal.vm.ci/jdk.vm.ci.meta=ALL-UNNAMED -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI TestNativeCodeBug
public class TestNativeCodeBug {
	public static void linkCode(Method method, byte[] code) {
		var jvmci = JVMCI.getRuntime().getHostJVMCIBackend();
		var rm = jvmci.getMetaAccess().lookupJavaMethod(method);
		jvmci.getCodeCache().setDefaultCode(rm, new HotSpotCompiledNmethod(method.getName(), code, code.length,
				new Site[]{new Mark(code.length - 5, 7 /*ENTRY_BARRIER_PATCH*/)}, new Assumptions.Assumption[0],
				new ResolvedJavaMethod[0], new HotSpotCompiledCode.Comment[0], new byte[0], 1, new DataPatch[0],
				true, 0, null, (HotSpotResolvedJavaMethod)rm, JVMCICompiler.INVOCATION_ENTRY_BCI, 1, 0, false));
	}

	public static native void dummy();

	public static void main(String[] args) throws Exception {
		var code = new byte[]{
				(byte)0xc3,
				0, 0, 0, // 4-byte align padding
				0x41, (byte)0x81, 0x7f, 0, 0 // barrier
		};
		linkCode(TestNativeCodeBug.class.getMethod("dummy"), code);
		dummy();
		System.out.println("GCGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCGC");
		System.gc();
		Thread.sleep(3000);
		dummy();
		System.out.println("OKOKOKOKOKOKOKOKOKOKOKOKOKOKOKOKOKOK");
	}
}
